(function () {
	init()

	$("#addcard").on('click', function() {
		window.location.href = 'regist.html'
	})


	
})()

function init () {
	var login = getCookie('isLogin') || ''
	var AuthCode = getCookie('isAuthCode') || ''
	var cardlist = []

	if (login === '') {
		window.location.href = 'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=login'
	} else if (AuthCode === '') {
	 	window.location.href = 'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=authwechatCode'
	} else {
		$.ajax({
			url:'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=getHealthCardList',
			type: 'get',
			dataType: 'json',
			success: function (resp) {
				if(resp.retcode === 0) {
					cardlist = resp.cards
					buildcardlist(cardlist)
				}else if(resp.retcode === 302) {
					window.location.href = resp.redirect_uri
				}
			}
		})

		
	}
}

function buildcardlist (list) {
	var length = 0
	var listhtml = ''
	if(list.length > 5) {
		length = 5
		$("#addcard").hide()
	} else {
		length = list.length

		$("#tips").html('您还可以办理' + (5 - list.length) + '张卡')
	}

	if (length === 0) {

		// let binded = getCookie('bindhealthcard')
		// if (!binded) {
		// 	window.location.href = 'https://healthcarddemo.tengmed.com/index.php?c=healthcard&a=authhealthCode'
		// 	setCookie('bindhealthcard', true)
		// }

		listhtml = '<div class="emptycard"><img src="img/nocard.png"/><p>暂无健康卡</p></div>'
	} else {
		for(var i = 0; i < length; i++) {
			listhtml = listhtml + '<a href="personal.html?name=' + list[i].name + 
					'&idCard=' + list[i].idCard + '&qrCodeText=' + list[i].qrCodeText + '&phone=' + list[i].phone1 +
					'" class="card">' +
					'<p class="name" id="name">' + list[i].name + '</p>' +
					'<p class="num" id="idcard">' + list[i].idCard + '</p>' +
					'<div class="qrcode">' +
						'<img title="qrcode" src="img/qrcode.jpg"/>' +
					'</div>' +
				'</a>'
		}
	}
	
	$("#cardlist").html(listhtml)
}

//获取cookie
function getCookie (c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1 
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) {
				c_end=document.cookie.length
			}
			return unescape(document.cookie.substring(c_start,c_end))
		} 
	}
	return ""
}

//获取url参数
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 匹配目标参数
  var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
  if (result != null) {
    return decodeURIComponent(result[2]);
  } else {
    return null;
  }
}

//设置cookie
function setCookie(c_name,value,expiredays) {
	var exdate = new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name + "=" + escape(value) +
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
